package com.napenalki.toto.service.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.napenalki.toto.domain.User;
import com.napenalki.toto.service.IllegalEntryException;
import com.napenalki.toto.service.UserService;

public class UserDetailsServiceImpl implements UserDetailsService {

    private UserService userService;

    @Autowired
    public UserDetailsServiceImpl(UserService userService) {
        this.userService = userService;
    }

    @Override
    public UserDetails loadUserByUsername(String userName)
            throws UsernameNotFoundException, DataAccessException {
        if (userName == null) {
            throw new IllegalEntryException("User name should not be null");
        }
        User userFromDb = userService.findUserByName(userName);

        if (userFromDb == null) {
            throw new UsernameNotFoundException("User with name " + userName
                    + " could not be found");
        }

        UserDetailsImpl details = new UserDetailsImpl();
        details.setUsername(userName);
        details.setPassword(userFromDb.getPassword());
        details.setAuthorities(userFromDb.getRole());

        return details;
    }

}
